<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="24" :xs="24">
        <!-- 数据筛选表单 -->
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="100px"
        >
          <!-- 数据筛选表单组件 -->
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="queryParams.roleName"
              placeholder="请输入角色名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <!-- 数据筛选操作按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置
            </el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="3">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd"
              >新增角色
            </el-button>
          </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-table v-loading="loading" :data="roleList">
          <!-- 数据表格列 -->
          <el-table-column label="角色ID" align="center" prop="id" />
          <el-table-column label="角色名称" align="center" prop="roleName" />
          <el-table-column label="角色编码" align="center" prop="roleKey" />
          <el-table-column label="描述" align="center" prop="roleDescription" />
          <!-- 数据行操作按钮 -->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-key"
                @click="handleMenu(scope.row)"
                >分配菜单</el-button
              >
              <el-button
                size="small"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >修改
              </el-button>
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 数据分页加载 -->
        <el-pagination
          :current-page="current"
          :page-sizes="[5, 10, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加修改role对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 数据编辑表单组件 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDescription">
          <el-input
            v-model="form.roleDescription"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <!-- 数据提交操作按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配菜单对话框 -->
    <el-dialog
      :title="menuTitle"
      :visible.sync="menuDialogFormVisible"
      width="300px"
    >
      <el-form :model="menuForm">
        <el-tree
          ref="menuTree"
          :data="menuTreeData"
          show-checkbox
          :check-strictly="checkStrictly"
          node-key="id"
          :default-expand-all="true"
          :props="defaultProps"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAuthRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
/** 导入axios Api */
import {
  listRoleByPage,
  getRole,
  addRole,
  updateRole,
  deleteRole,
  authMenu,
} from "@/api/role";
import { treeMenu } from "@/api/menu";
export default {
  name: "Role",
  data() {
    return {
      menuId: null,
      roleKey: null,
      roleName: null,
      defaultProps: {
        label: "menuName",
      },
      checkStrictly: true,
      menuTreeData: [],
      menuForm: {},
      menuDialogFormVisible: false,
      menuTitle: "",
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 当前页
      current: 0,
      // 每页数据量
      pageSize: 0,
      // Role表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据查询参数
      queryParams: {
        current: 1,
        id: "",
        pageSize: 10,
        roleDescription: "",
        roleKey: "",
        roleName: "",
        sortField: "create_time",
        sortOrder: "",
      },
      // 数据编辑表单
      form: {},
      // 表单数据校验规则
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleKey: [
          { required: true, message: "角色编码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    resetMenuForm() {
      this.menuForm = {
        roleId: null,
        menuIds: [],
      };
    },
    /** 处理分配菜单 */
    handleMenu(row) {
      this.menuForm.id = row.id;
      this.menuId = row.id;
      this.menuTitle = "为角色[" + row.roleName + "]分配菜单";
      this.menuDialogFormVisible = true;
      treeMenu().then((response) => {
        this.menuTreeData = response.data;
      });
      getRole(this.menuForm.id).then((response) => {
        var menus = response.data.roleMenuVo.menuList;
        if (menus) {
          const menuIds = menus.map((item) => item.id);
          this.$refs.menuTree.setCheckedKeys(menuIds);
        }else{
          this.$refs.menuTree.setCheckedKeys([])
        }
      });
    },
    /** 提交分配菜单表单 */
    submitAuthRole() {
      this.menuForm.menuIds = this.$refs.menuTree.getCheckedKeys();
      this.menuForm.roleId = this.menuId;
      delete this.menuForm.id;
      authMenu(this.menuForm).then(() => {
        this.$message.success("修改成功");
        this.menuDialogFormVisible = false;
        this.resetMenuForm();
      });
    },
    /** 查询Role数据列表 */
    getList() {
      this.loading = true;
      listRoleByPage(this.queryParams).then((response) => {
        this.roleList = response.data.records;
        this.total = response.data.total;
        this.current = this.queryParams.current;
        this.pageSize = this.queryParams.pageSize;
        this.loading = false;
      });
    },
    /** 处理分页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },

    /** 数据编辑对话框取消按钮 */
    cancel() {
      this.open = false;
      this.resetForm();
    },

    /** 数据编辑表单清空 */
    resetForm() {
      this.form = {
        roleName: null,
        roleKey: null,
        roleDescription: null,
      };
    },

    /** 数据筛选参数重置按钮 */
    resetQueryParams() {
      this.queryParams.current = 1;
      this.queryParams.pageSize = 5;
    },

    /** 数据筛选搜索按钮 */
    handleQuery() {
      this.resetQueryParams();
      this.getList();
      this.$message.success("查询成功");
    },

    /** 数据筛选重置按钮 */
    resetQuery() {
      this.queryParams = {
        current: 1,
        id: "",
        pageSize: 10,
        roleDescription: "",
        roleKey: "",
        roleName: "",
        sortField: "create_time",
        sortOrder: "",
      };
      this.getList();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.title = "添加Role";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm();
      getRole(row.id).then((response) => {
        this.roleName = response.data.roleName;
        this.roleKey = response.data.roleKey;

        this.form = response.data;
        this.open = true;
        this.title = "修改Role";
      });
    },

    /** 数据提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id === undefined) {
            addRole(this.form).then(() => {
              this.$message.success("新增成功");
              this.open = false;
              this.title = "";
              this.getList();
            });
          } else {
            if (this.form.roleKey == this.roleKey) {
              delete this.form.roleKey;
            }
            if (this.form.roleName === this.roleName) {
              delete this.form.roleName;
            }
            updateRole(this.form).then((response) => {
              this.$message.success("修改成功");
              this.open = false;
              this.title = "";
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除名称为"' + row.roleName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return deleteRole({ id: row.id });
        })
        .then(() => {
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
  